package com.kuhyygy.status;

import com.kuhyygy.MainActivity;
import com.kuhyygy.R;

import android.app.IntentService;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class NotificationService extends IntentService {

	public NotificationService() {
		super("NotificationService");
	}

	@Override
	protected void onHandleIntent(Intent arg0) {
		try {
			Log.i("NotificationService", "notify...");
			showNotification(false);
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void showNotification(boolean finish) {
		Intent i = new Intent(NotificationService.this, MainActivity.class);
		Builder nb = new Notification.Builder(NotificationService.this);
		Resources res = NotificationService.this.getResources();
		
		/**
		 * 下面信息必填
		 */
		nb.setTicker("开始下载文件...");	// 状态栏文字
		nb.setSmallIcon(R.drawable.notify_image48);	// 状态栏图标
		nb.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.notify_image48));	// 好像无效
		nb.setContentTitle("开始下载");	// 扩展栏的标题
		nb.setContentText("下载文件");	// 扩展栏的内容
		
		/**
		 * 会有声音,振动,以及呼吸灯通知
		 * (不过要在AndroidManifest.xml里设置<uses-permission android:name="android.permission.VIBRATE"/>)
		 */
		nb.setDefaults(Notification.DEFAULT_ALL);
		nb.setWhen(System.currentTimeMillis());
		PendingIntent intent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
		nb.setContentIntent(intent);
		NotificationManager nfyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nb.setAutoCancel(true);
		Notification n = nb.build();
		nfyManager.notify(R.id.addMsg, n);
		
	}
	
	public static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

}
